<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:drugMovements:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:drugMovements:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:drugMovements:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:drugMovements:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drugMovementsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="变动记录ID" align="center" prop="movementId" /> -->
      <el-table-column label="药品名称" align="center">
        <template #default="scope">
          <span>{{ getDrugName(scope.row.drugId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="变动类型" align="center" prop="movementType">
        <template #default="scope">
          <dict-tag :options="drug_changes_status" :value="scope.row.movementType"/>
        </template>
      </el-table-column>
      <el-table-column label="变动数量" align="center" prop="quantity" />
      <el-table-column label="操作员姓名" align="center">
        <template #default="scope">
          <span>{{ getOperatorName(scope.row.operatorId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" align="center">
        <template #default="scope">
          <span>{{ getUserName(scope.row.userId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="变动日期" align="center" prop="movementDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.movementDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:drugMovements:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:drugMovements:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品变动明细对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="drugMovementsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="药品ID" prop="drugId">
          <el-input v-model="form.drugId" placeholder="请输入药品ID" />
        </el-form-item>
        <el-form-item label="变动数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入变动数量" />
        </el-form-item>
        <el-form-item label="操作员ID" prop="operatorId">
          <el-input v-model="form.operatorId" placeholder="请输入操作员ID" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="变动日期" prop="movementDate">
          <el-date-picker clearable
            v-model="form.movementDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择变动日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DrugMovements">
import { listDrugMovements, getDrugMovements, delDrugMovements, addDrugMovements, updateDrugMovements } from "@/api/manage/drugMovements";
import { listUser } from "@/api/system/user";
import { listDrugs } from "@/api/manage/drugs";

const { proxy } = getCurrentInstance();
const { drug_changes_status } = proxy.useDict('drug_changes_status');

const drugMovementsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const drugMap = ref({}); // 用于存储药品 ID 到药品名称的映射
const operatorMap = ref({}); // 用于存储操作员 ID 到操作员姓名的映射
const userMap = ref({}); // 用于存储用户 ID 到用户姓名的映射

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    movementId: null,
    drugId: null,
    movementType: null,
    quantity: null,
    operatorId: null,
    userId: null,
    movementDate: null,
    remarks: null,
    createTime: null,
    updateTime: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询所有药品信息并构建映射 */
async function fetchAllDrugs() {
  const response = await listDrugs();
  const drugs = response.rows; 
  if (drugs && drugs.length > 0) {
    drugs.forEach(drug => {
      drugMap.value[drug.drugId] = drug.drugName;
    });
  }
}

/** 查询所有操作员和用户信息并构建映射 */
async function fetchAllUsers() {
  const response = await listUser();
  const users = response.rows; 
  if (users && users.length > 0) {
    users.forEach(user => {
      operatorMap.value[user.userId] = user.nickName;
      userMap.value[user.userId] = user.nickName;
    });
  }
}

/** 查询药品变动明细列表 */
async function getList() {
  loading.value = true;
  await Promise.all([fetchAllDrugs(), fetchAllUsers()]); // 先获取所有药品、操作员和用户信息
  listDrugMovements(queryParams.value).then(response => {
    drugMovementsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    movementId: null,
    drugId: null,
    movementType: null,
    quantity: null,
    operatorId: null,
    userId: null,
    movementDate: null,
    remarks: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("drugMovementsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.movementId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加药品变动明细";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _movementId = row.movementId || ids.value
  getDrugMovements(_movementId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改药品变动明细";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["drugMovementsRef"].validate(valid => {
    if (valid) {
      if (form.value.movementId != null) {
        updateDrugMovements(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDrugMovements(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _movementIds = row.movementId || ids.value;
  proxy.$modal.confirm('是否确认删除药品变动明细编号为"' + _movementIds + '"的数据项？').then(function() {
    return delDrugMovements(_movementIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/drugMovements/export', {
    ...queryParams.value
  }, `drugMovements_${new Date().getTime()}.xlsx`)
}

// 获取药品名称的函数
function getDrugName(drugId) {
  return drugMap.value[drugId] || '无';
}

// 获取操作员姓名的函数
function getOperatorName(operatorId) {
  return operatorMap.value[operatorId] || '无';
}

// 获取用户姓名的函数
function getUserName(userId) {
  return userMap.value[userId] || '无';
}



getList();
</script>
